/**
 * @param {string} s
 * @param {string} p
 * @return {number[]}
 */
export var findAnagrams = function (s, p) {
  // 典型滑窗
  if (p.length > s.length) return []

  let result = [] // 记录结果并作为返回值
  let left = 0,
    right = 0 // 标记窗口的左右端 窗口为左开右闭的区间 e.g. [1,4)
  let win = {},
    need = {} // 用 win 记录当前窗口内各个字符的数量，need 记录各个字符“需要满足”的数量
  let valid = 0 // 标记位，记录“有多少个字符 已经达到了需要的数量”

  // 完成 need 和 window 的初始化
  for (const item of p) {
    if (need[item] === undefined) need[item] = 0
    need[item]++
    win[item] = 0
  }
  let needSize = Object.keys(need).length

  while (right < s.length) {
    const c = s[right]
    right++
    if (need[c] !== undefined) {
      //console.log(c)
      win[c]++
      if (win[c] === need[c]) valid++
    }
    // 加入结果
    // console.log(left,right,win,valid)
    if (valid === needSize) {
      result.push(left)
    }

    while (right - left >= p.length) {
      const d = s[left]
      left++
      if (win[d] !== undefined) {
        if (win[d] === need[d]) valid--
        win[d]--
      }
      //console.log(window,left,right)
    }
  }
  return result
}
